package com.hedl.classroom.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hedl.classroom.feignclient.CheckCodeClient;
import com.hedl.classroom.mapper.XcUserMapper;
import com.hedl.classroom.model.dto.AuthParamsDto;
import com.hedl.classroom.model.dto.XcUserExt;
import com.hedl.classroom.model.po.XcUser;
import com.hedl.classroom.service.AuthService;
import io.micrometer.core.instrument.binder.BaseUnits;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Big Watermelon
 * @description 根据密码认证的方式
 * @date 2023/12/09/11:41
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {

    @Resource
    private XcUserMapper xcUserMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private CheckCodeClient checkCodeClient;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //获取账号
        String username = authParamsDto.getUsername();
        //获取明文密码
        String password = authParamsDto.getPassword();

        //输入的验证码
        String checkcode = authParamsDto.getCheckcode();
        //验证码对应的key
        String checkcodekey = authParamsDto.getCheckcodekey();

        if (StringUtils.isEmpty(checkcodekey) || StringUtils.isEmpty(checkcodekey)){
            throw new RuntimeException("请输入验证码！");
        }

        //远程调用验证码服务接口，校验验证码
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if (verify == null || !verify){
            throw new RuntimeException("验证码输出入错误！");
        }


        //账号是否存在,根据username账号查询数据库
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        //查询用户不存在，返回null即可；spring security框架抛出异常用户不存在
        if (xcUser == null){
            throw new RuntimeException("账号不存在！");
        }

        //验证密码是否正确
        boolean matches = passwordEncoder.matches(password, xcUser.getPassword());
        if (!matches){
            throw new RuntimeException("账号或密码错误！");
        }

        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser,xcUserExt);

        return xcUserExt;
    }
}
